package com.miage.kangourou.server.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.miage.kangourou.client.beans.Ue;

public class UeDao extends GenericDao<Ue> {

	public UeDao(Connection connect) {
		super(connect);
	}

	public Ue findById(int id) throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM UE WHERE ID_UE = " + id);

		Ue evt;

		if (result.next()) {
			evt = new Ue(result.getInt("ID_UE"), result.getString("INTITULE"));
		} else {
			evt = new Ue();
		}

		result.close();

		return evt;
	}

	public List<Ue> findAll() throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM UE");

		List<Ue> all = new ArrayList<Ue>();
		while (result.next()) {
			all
			.add(new Ue(result.getInt("ID_UE"), result
					.getString("INTITULE")));
		}

		result.close();

		return all;
	}

	public void create(Ue ue) throws SQLException {
		if (ue instanceof Ue && !ue.equals(null)) {

			connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"INSERT INTO UE (ID_UE, INTITULE) VALUES (" + ue.getId_ue()
							+ ", \"" + ue.getIntitule() + "\"");
		}
	}

	public boolean alreadyExist(Ue ue) throws SQLException {
		boolean exist = false;

		if (ue instanceof Ue && !ue.equals(null)) {

			ResultSet result = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"SELECT * FROM UE WHERE ID_UE = " + ue.getId_ue());

			if (result.next()) {
				exist = true;
			}

			result.close();
		}

		return exist;
	}

	public boolean delete(int idUe){
		boolean deleted = true;

		try {
			connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"DELETE FROM UE WHERE ID_UE = " + idUe);

		} catch (SQLException e) {
			e.printStackTrace();
			deleted = false;
		}



		return deleted;
	}

}
